package com.clei.config.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

/**
 * Redis Key Expire Listener
 *
 * @author KIyA
 * @date 2021-10-10
 */
@Component
public class RedisKeyExpireListener implements MessageListener {

    private RedisTemplate<String, Object> redisTemplate;

    private Logger logger = LoggerFactory.getLogger(RedisKeyExpireListener.class);

    public RedisKeyExpireListener(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        RedisSerializer<?> keySerializer = redisTemplate.getKeySerializer();
        // RedisSerializer<?> valueSerializer = redisTemplate.getValueSerializer();
        try {
            String channel = String.valueOf(keySerializer.deserialize(message.getChannel()));
            String key = String.valueOf(keySerializer.deserialize(message.getBody()));
            String channel2 = String.valueOf(keySerializer.deserialize(bytes));

            logger.info("channel : {}, key : {}, channel2 : {}", channel, key, channel2);
        } catch (Exception e) {
            logger.error("message handle exception ", e);
        }
    }
}
